package com.macrohard.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.macrohard.admin.service.AddressService;
import com.macrohard.common.base.response.R;
import com.macrohard.mapper.domain.Address;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/address")
@Validated
@Api(tags = "地址接口")
@RequiredArgsConstructor
public class AddressController {

	private final AddressService addressService;

	@ApiOperation("分页获取地址")
	@GetMapping
	public R get(@NotNull Integer current, @NotNull Integer pageSize) {
		Page<Address> page = new Page<>(current, pageSize);
		LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
		page = addressService.page(page, queryWrapper);
		return R.ok("ok", page);
	}

	@ApiOperation("获取所有地址名称和id")
	@GetMapping("names")
	public R get() {
		List<Address> addresses = addressService.listAllNameAndId();
		List<Map<String, Object>> res = addresses.stream().map(it -> {
			Map<String, Object> tmp = new HashMap<>();
			tmp.put("id", it.getId());
			tmp.put("name", it.getName());
			return tmp;
		}).collect(Collectors.toList());
		return R.ok("ok", res);
	}

	@ApiOperation("根据id获取地址")
	@GetMapping("{id}")
	public R get(@PathVariable Integer id) {
		return R.ok("ok", addressService.getById(id));
	}

	@ApiOperation("添加地址")
	@PostMapping
	public R add(@RequestBody Address address) {
		return R.wrapEffectResult(addressService.add(address));
	}

	@ApiOperation("修改地址")
	@PutMapping
	public R update(@RequestBody Address address) {
		return R.wrapEffectResult(addressService.modify(address));
	}

	@ApiOperation("根据id删除地址")
	@DeleteMapping("{id}")
	public R delete(@PathVariable Integer id) {
		return R.wrapEffectResult(addressService.removeOne(id));
	}

	@ApiOperation("批量删除地址")
	@DeleteMapping
	public R delete(@RequestBody List<Integer> ids) {
		return R.wrapEffectResult(addressService.removeByIds(ids));
	}
}
